package org.onionframework.faces.web.action.support;

import java.util.Iterator;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * 工具Bean，一般用于前台表达式语言，例如：#{tools.success}
 * 
 * @author allan
 *
 */
@Component("faces.tools")
@Scope("application")
public class ToolsBean {
	/**
	 * 将回车和空格转换成相应的HTML字符
	 * @param str
	 * @return
	 */
	public String formatContentStr(String str) {
		String newString = str.replaceAll("<.*?>", "");
		newString = newString.replaceAll("\n", "<br/>");
		newString = newString.replaceAll(" ", "&#160;");
		return newString;
	}
	
	/**
	 * 转换为整型
	 * @param value
	 * @return
	 */
	public int intValue(double value) {
		return (int) value;
	}
	
	/**
	 * 获取系统时间
	 * @param value
	 * @return
	 */
	public long getSysTime() {
		return System.currentTimeMillis();
	}
	
	public String getRandomString(int length){
		return RandomStringUtils.random(6,"abcdefghijklmnopqrstuvwxyz1234567890");
	}
	
	/**
	 * 有错误消息输出
	 * @return
	 */
	public boolean isSuccess() {
		Iterator<FacesMessage> messages = FacesContext.getCurrentInstance().getMessages();
		while(messages.hasNext()){
			if(FacesMessage.SEVERITY_ERROR == messages.next().getSeverity())
				return false;
		}

		return true;
	}
	
	/**
	 * 链接字符串
	 * @param args
	 * @return
	 */
	public String concat(Object ...args) {
		if(args.length == 0) return "";
		StringBuilder result = new StringBuilder("");
		for(Object o : args)
			result.append(o == null ? "" : o.toString());
		
		return result.toString();
	}
	
	
	public boolean contains(Object[] array,Object value){
		return ArrayUtils.contains(array, value);
	}
	
	public String getTableRender(){
		if(!this.isSuccess())
			return "reRenderPlaceHolder";
		else
			return "dataTable dataTableScroller queryFields";
	}
	
	public String getTableRender(String addtional){
		if(!this.isSuccess())
			return "reRenderPlaceHolder";
		else{
			if(StringUtils.isBlank(addtional))
				return "dataTable dataTableScroller queryFields";
			else
				return "dataTable dataTableScroller queryFields," + addtional;
		}
	}
}
